package org.mathcloud.math.core.scilab.operator.algebra;

import org.apache.log4j.Logger;
import org.mathcloud.math.core.common.operator.algebra.Log;
import org.mathcloud.math.core.common.signature.QuantityObjectSignature;
import org.mathcloud.math.core.scilab.factory.ScilabQuantityObjectFactory;
import org.mathcloud.math.core.scilab.manager.ScilabSupervisor;
import org.mathcloud.math.core.scilab.operator.ScilabBinaryOperator;
import org.mathcloud.math.core.scilab.quantity.ScilabQuantityObject;
import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.types.ScilabDouble;

public class ScilabLog extends ScilabBinaryOperator implements Log
{
	public ScilabLog()
	{
		super();
		signature.setMMLContentTag("log");
	}

	@Override
	public void calculate()
	{
		if (getResultSignature()!=null)
	  {
	    String sciJob;
	    String tmpVar = "tmp_"+ScilabSupervisor.getVarId();
			ScilabQuantityObject tOp1 = ScilabQuantityObjectFactory.getInstance(operand1);
			ScilabQuantityObject tOp2 = ScilabQuantityObjectFactory.getInstance(operand2);
			sciJob = tmpVar;
			if (tOp2==null)
			{	
				sciJob = sciJob + "=log10("+ tOp1.getVarName()+")";
			} else
			{
				sciJob = sciJob + "=log("+ tOp1.getVarName()+")";
		    sciJob = sciJob + "/log("+tOp2.getVarName()+")";				
			}			
	    sciJob +=";";  
	    if (sciEngine.exec(sciJob))
	    {
	    	log.info(sciJob);
	    	try
				{
	    		ScilabDouble tRes = (ScilabDouble)sciEngine.get(tmpVar);
	      	res = ScilabQuantityObjectFactory.getInstance(tRes);
					sciJob = "clear "+tmpVar+";";
					if (sciEngine.exec(sciJob))
						log.info(sciJob);					      	
				} catch (JavasciException e)
				{
					log.error(e);
				}
	    }
	    else
	    {
	    	res = null;
	    	log.info(sciJob + " - " + sciEngine.getLastErrorMessage());
	    }
	  }    								
	}	
	
	@Override
	public QuantityObjectSignature getResultSignature()
	{
    if (operand1!=null)
    {
    	return operand1.getSignature();
    } else return null;
	}

	
	private static final Logger log = Logger.getLogger(ScilabLog.class);

}
